﻿using ExamServerBLL;
using ExamServerViewModels;
using HZH_Controls.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ExamUtils;

namespace Exam_Server.childForms
{
    // 声明应用配置的委托
    public delegate void ApplyConfigEventHandler();
    public partial class FrmSetting : Form
    {
        // SettingServer业务逻辑层
        private static SettingService SettingService = new SettingService();

        // 声明事件
        public event ApplyConfigEventHandler ApplyConfig;

        public FrmSetting()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 获取连接服务状态
        /// </summary>
        /// <returns></returns>
        public bool GetSocketServiceStatus() {
            return SettingService.GetSocketStatus();
        }

        /// <summary>
        /// 开启socket监听服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Service_BtnClick(object sender, EventArgs e)
        {
            int socketPort;
            ServerConfiguration config = SettingService.GetConfiguration();
            int originalPort = config.SocketPort;
            try
            {
                socketPort = Convert.ToInt32(textBox_port.Text);
                if (CheckUtils.CheckPort(socketPort))   //检验端口号
                {
                    // 写配置文件
                    config.SocketPort = socketPort;
                    SettingService.WriteConfig(config);
                }
                else
                {
                    // 提示用户
                    FrmDialog.ShowDialog(this, "错误: 端口号不在1-65535范围内!\n请跟换正确端口号再试!", "错误");
                    return;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("异常: 端口号异常  " + ex.Message);
                FrmDialog.ShowDialog(this, "错误: 端口号格式错误!\n请跟换正确端口号再试!", "错误");
                this.textBox_port.Text = originalPort.ToString();
                return;
            }

            // 校验是否存在连接(存在连接则提示用户)
            bool IsOpen = GetSocketServiceStatus();

            if (IsOpen)
            { /// 服务已经打开
                if (FrmDialog.ShowDialog(this, "警告: 您即将关闭socket连接服务,将强制断开所有已建立的连接!\n是否关闭socket连接服务?", "警告", true)
                    == System.Windows.Forms.DialogResult.OK)
                {
                    SettingService.StopSocketServer();
                    ChangeScoektLabel(false);
                    OnApplyConfig();
                }
            }
            else
            { /// 服务未打开

                // 写配置文件
                // 启动socket服务
                bool flag = SettingService.StartSocketServer();
                if (flag)
                {
                    FrmTips.ShowTips(null, "socket服务已开启", 3000, false, ContentAlignment.TopCenter, null, TipsSizeMode.Small, null, TipsState.Success);
                    FrmTips.ReshowTips();
                    // 更改标签内容
                    ChangeScoektLabel(flag);
                    OnApplyConfig();
                }
                else
                {
                    FrmDialog.ShowDialog(this, "错误: 启动Socket连接服务失败!\n原因: 可能是端口号被占用,请跟换端口号再试!", "未知错误");
                    return;
                }
            }
        }

        /// <summary>
        /// 更改socket界面标签
        /// </summary>
        /// <param name="isON"></param>
        private void ChangeScoektLabel(bool isON)
        {
            if (isON)
            { // 连接服务被打开
                this.label_socketStatus.Text = "√ 服务已开启";
                this.label_socketStatus.ForeColor = Color.FromArgb(60, 179, 113);
                this.btn_Service.BtnText = "关闭服务";
                this.textBox_port.Enabled = false;
            }
            else
            { // 连接服务被关闭
                this.label_socketStatus.Text = "× 服务已关闭";
                this.label_socketStatus.ForeColor = Color.FromArgb(160, 160, 160);
                this.btn_Service.BtnText = "启动服务";
                this.textBox_port.Enabled = true;
            }
        }



        /// <summary>
        /// 系统设置窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmSetting_Load(object sender, EventArgs e)
        {
            Init();
        }

        /// <summary>
        /// 数据库配置确认按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_sqlOK_BtnClick(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 初始化窗体内容
        /// </summary>
        private void Init()
        {
            // 初始化时候不触发Changed事件
            SetChangeEventStatus(false);
            // 获取socket状态
            if (SettingService.GetSocketStatus())
            {
                ChangeScoektLabel(true);
            }
            else
            {
                ChangeScoektLabel(false);
            }

            // 获取设置信息
            SettingServiceViewModel info = SettingService.GetSettingInfo();
            //if (info.IsShowAllIp)
            //{
            //    this.label_IP.Text = info.AllIpAddress;
            //}
            //else
            //{
            //    this.label_IP.Text = info.IpAddress;
            //}
            this.label_IP.Text = info.IpAddress; // 设置界面只显示物理网卡ip
            this.textBox_port.Text = info.SocketPort;
            this.checkBox_ipPort.Checked = info.IsShowIpAndPort;
            this.checkBox_time.Checked = info.IsShowTime;
            this.checkBox_onlineNum.Checked = info.IsShowOnlineNum;
            this.checkBox_examNum.Checked = info.IsShowExamNum;
            this.checkBox_bubble.Checked = info.IsShowOnlineBubble;
            this.comboBox_ipNum.SelectedIndex = info.IsShowAllIp ? 1 : 0;
            this.comboBox_timePattern.SelectedIndex = comboBox_timePattern.Items.IndexOf(info.TimePattern);
            this.textBox_host.Text = info.SqlHost;
            this.textBox_sqlPort.Text = info.SqlPort;
            this.textBox_username.Text = info.SqlUsername;
            this.textBox_pwd.Text = info.SqlPassword;

            // 绑定changed事件
            SetChangeEventStatus(true);
        }

        /// <summary>
        /// 设置控件的change事件
        /// </summary>
        /// <param name="isUsed"></param>
        private void SetChangeEventStatus(bool isUsed)
        {
            if (isUsed)
            {
                // 绑定事件
                this.checkBox_ipPort.CheckedChanged += checkBox_ipPort_CheckedChanged;
                this.checkBox_time.CheckedChanged += checkBox_time_CheckedChanged;
                this.checkBox_examNum.CheckedChanged += checkBox_examNum_CheckedChanged;
                this.checkBox_onlineNum.CheckedChanged += checkBox_onlineNum_CheckedChanged;
                this.checkBox_bubble.CheckedChanged += checkBox_bubble_CheckedChanged;
                this.comboBox_ipNum.SelectedIndexChanged += comboBox_ipNum_SelectedIndexChanged;
                this.comboBox_timePattern.SelectedIndexChanged += comboBox_timePattern_SelectedIndexChanged;
            }
            else
            {
                // 解绑事件
                this.checkBox_ipPort.CheckedChanged -= checkBox_ipPort_CheckedChanged;
                this.checkBox_time.CheckedChanged -= checkBox_time_CheckedChanged;
                this.checkBox_examNum.CheckedChanged -= checkBox_examNum_CheckedChanged;
                this.checkBox_onlineNum.CheckedChanged -= checkBox_onlineNum_CheckedChanged;
                this.checkBox_bubble.CheckedChanged -= checkBox_bubble_CheckedChanged;
                this.comboBox_ipNum.SelectedIndexChanged -= comboBox_ipNum_SelectedIndexChanged;
                this.comboBox_timePattern.SelectedIndexChanged -= comboBox_timePattern_SelectedIndexChanged;
            }
        }


        /// <summary>
        /// 主界面应用配置事件触发函数
        /// </summary>
        protected virtual void OnApplyConfig()
        {
            ApplyConfig?.Invoke();
        }



        private void checkBox_ipPort_CheckedChanged(object sender, EventArgs e)
        {
            // 读取原有配置信息
            ServerConfiguration config = SettingService.GetConfiguration();
            bool flag = this.checkBox_ipPort.Checked;
            config.IsShowIpAndPort = flag;
            // 写配置文件
            if (SettingService.WriteConfig(config))
            {
                // 主界面应用配置, 触发事件
                OnApplyConfig();
            }
            if (flag)
            {
                this.comboBox_ipNum.Enabled = true;
            }
            else
            {
                this.comboBox_ipNum.Enabled = false;
            }
        }

        private void checkBox_time_CheckedChanged(object sender, EventArgs e)
        {
            ServerConfiguration config = SettingService.GetConfiguration();
            bool flag = this.checkBox_time.Checked;
            config.IsShowTime = flag;
            if (SettingService.WriteConfig(config))
            {
                OnApplyConfig();
            }
            if (flag)
            {
                this.comboBox_timePattern.Enabled = true;
            }
            else
            {
                this.comboBox_timePattern.Enabled = false;
            }
        }

        private void checkBox_examNum_CheckedChanged(object sender, EventArgs e)
        {
            ServerConfiguration config = SettingService.GetConfiguration();
            config.IsShowExamNum = this.checkBox_examNum.Checked;
            if (SettingService.WriteConfig(config))
            {
                OnApplyConfig();
            }
        }

        private void checkBox_onlineNum_CheckedChanged(object sender, EventArgs e)
        {
            ServerConfiguration config = SettingService.GetConfiguration();
            config.IsShowOnlineNum = this.checkBox_onlineNum.Checked;
            if (SettingService.WriteConfig(config))
            {
                OnApplyConfig();
            }
        }

        private void checkBox_bubble_CheckedChanged(object sender, EventArgs e)
        {
            ServerConfiguration config = SettingService.GetConfiguration();
            config.IsShowOnlineBubble = this.checkBox_bubble.Checked;
            if (SettingService.WriteConfig(config))
            {
                OnApplyConfig();
            }
        }

        private void comboBox_ipNum_SelectedIndexChanged(object sender, EventArgs e)
        {
            ServerConfiguration config = SettingService.GetConfiguration();
            config.IsShowAllIp = this.comboBox_ipNum.SelectedIndex == 1;
            if (SettingService.WriteConfig(config))
            {
                OnApplyConfig();
            }
        }

        private void comboBox_timePattern_SelectedIndexChanged(object sender, EventArgs e)
        {
            ServerConfiguration config = SettingService.GetConfiguration();
            config.TimePattern = this.comboBox_timePattern.Text;
            if (SettingService.WriteConfig(config))
            {
                OnApplyConfig();
            }
        }
    }
}
